<?php
namespace app\system\controller;

use app\system\model\ContentclassModel;

/**
 * 广告分类
 *
 * @ author zy <741599086@qq.com>
 * */
 
class Contentclass extends Common
{
    /**
     * 列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index() {
    	$model = new ContentclassModel();
    	$list = $model->selectClass([], 20, 'sort desc,id desc');
    	$this->assign('list' , $list) ;

    	return $this->fetch() ;
	}

    /**
     * 修改
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	public function save()
	{

        $model = new ContentclassModel();
        if (isAjaxPost()) {

            $data = input ('post.');
            $id = input('post.id', 0, 'intval');
            unset($data['id']);
            $validate = new \app\system\validate\Contentclass();
            if (!$validate->check($data)) {
                return $this->jsonError($validate->getError());
            }

            if ($id <= 0) {
                $data['time'] = time();
                if ($model->insert($data)) {
                    return $this->jsonSuccess('添加成功');
                } else {
                    return $this->jsonError('添加失败');
                }
            } else {
                if ($model->update($data, ['id'=>$id]) !== false) {
                    return $this->jsonSuccess('修改成功');
                } else {
                    return $this->jsonError('修改失败');
                }
            }

        }
				
        $id = input('id') ;
        if ($id > 0) {
            $this->assign('data', $model->where('id', $id)->find());
        }

        return $this->fetch() ;
	}
	
	/**
	 * 排序
	 * */
	public function saveSort()
	{
        !isAjaxPost() && die;
        $model = new ContentclassModel();
        $sort = input('post.');
        foreach ($sort as $k => $v) {
            $model->where('id', $k)->update(['sort' => $v]);
        }
        return $this->jsonSuccess('修改成功');
	}
	
	/**
	 * 删除
	 */
	public function delClass()
	{
        !isAjaxPost() && die;
        $model = new ContentclassModel();
        $id = input('post.id', 0, 'intval');

        if ($id > 0 && $model->where('id', $id)->delete() !== false) {
            return $this->jsonSuccess('删除成功');
        } else {
            return $this->jsonError('删除失败');
        }
	}
	
}
